<?php

namespace app\admin\model;

class Rule extends \think\Model
{
    protected $name = 'rule';
    protected $json = ['options'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    public static function onBeforeInsert($model)
    {
        if (empty($model['options'])) $model['options'] = [];
        if (empty($model['type'])) $model['type'] = 1;
    }

    public static function onBeforeUpdate($model)
    {
        $list = self::where(['type' => 1])->select();
        $children_ids = children_ids($list, $model['id']);
        if (in_array($model['pid'], $children_ids) || $model['id'] == $model['pid']) {
            throw new \Exception('上级节点不能为自己或自己的子节点');
        }
    }

    public static function onBeforeDelete($model)
    {
        //检测是否有角色包含此节点
        foreach (Group::where(['type' => 1])->column('rules') as $v) {
            if ($v == '*') continue;
            if(in_array($model['id'],explode(',',$v))){
                throw new \Exception('有角色正在使用此节点');
            }
        }
        //检测是否存在子节点
        if (self::where(['pid' => $model['id'], 'type' => 1])->find()) {
            throw new \Exception('请先删除子节点');
        }
    }

    /**
     * 菜单路径
     */
    public static function menu_path($list, $id)
    {
        $arr = [];
        foreach ($list as $k => $v) {
            if ($v['id'] == $id) {

                $arr[] = $v;
                $arr = array_merge($arr, self::menu_path($list, $v['pid']));
            }
        }
        return $arr;
    }

    public function getOptionssAttr($list,$data)
    {
        $arr = [];
        foreach ($data['options'] as $v) {
            if($v['key']&&$v['value'])
            $arr[$v['key']] = $v['value'];
        }
        return $arr;
    }
}
